package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private DeptService deptService;
    @Autowired
    private EmpExprService empExprService;
    @Override
    public PageResult<Emp> findPage(EmpQueryParam param) {
        //1. 设置分页参数(MyBatis-Plus)
        Page<Emp> empPage = new Page<>(param.getPage(), param.getPageSize());

        // 按照最后修改时间降序排序
        empPage.addOrder(OrderItem.desc("update_time"));

        //完善2：条件查询
        LambdaQueryWrapper<Emp> queryWrapper= new LambdaQueryWrapper<Emp>()
                .like(!StringUtils.isEmpty(param.getName()), Emp::getName, param.getName())
                .eq(param.getGender() != null, Emp::getGender, param.getGender())
                .between(param.getBegin() != null && param.getEnd() != null,Emp::getEntryDate,param.getBegin(), param.getEnd());

        //2.调用分页查询方法
        this.page(empPage,queryWrapper);

        //完善1：关联查询部门名称
        List<Emp> empList = empPage.getRecords();
        empList.forEach(emp -> {
            //根据部门ID查询部门名称
            Integer deptId = emp.getDeptId();
            Dept dept = deptMapper.selectById(deptId);

            if (dept != null){
                //设置部门名称
                emp.setDeptName(dept.getName());
            }
        });

        return new PageResult<>(empPage.getTotal(), empPage.getRecords());
    }

    //添加员工信息

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveEmpAndExpr(Emp emp) {
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        this.save(emp);

        // 调用service层方法保存员工工作经历信息
        List<EmpExpr> exprList = emp.getExprList();

        if (exprList == null || exprList.isEmpty()){
            return;
        }
        // 添加工作经历所属员工
        exprList.forEach(expr -> expr.setEmpId(emp.getId()));
        empExprService.saveBatch(exprList);
    }

    /**
     * 根据id查询员工信息
     */
    @Override
    public Emp getEmpById(Integer id) {
        Emp emp = getById(id);

        // 部门名称
        emp.setDeptName(deptService.getById(emp.getDeptId()).getName());
        // 工作经历列表
        emp.setExprList(empExprService.list(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, id)));
        return emp;
    }

    /**
     * 修改员工信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmp(Emp emp) {
        //1.修改员工基本信息
        emp.setUpdateTime(LocalDateTime.now());
        updateById(emp);
        //2.删除员工工作经历信息
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, emp.getId()));

        //3.添加员工工作经历信息
        List<EmpExpr> exprList = emp.getExprList();

        if (exprList != null && !exprList.isEmpty()){
            //为每条工作经历添加emp_id
            exprList.forEach(expr -> expr.setEmpId(emp.getId()));

            //批量保存员工工作经历信息
            empExprService.saveBatch(exprList);
        }
    }

    /**
     * 批量删除
     *
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByIds(List<Integer> ids) {
        //1.删除员工基本信息
        removeByIds(ids);

        //2.删除员工工作经历信息
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().in(EmpExpr::getEmpId, ids));
    }
}
